<template>
  <div class="container">
    <div class="left">
      <div class="top-left">
        <label>选择收货地</label>
        <el-button
          class="add-place-button"
          @click="
            (addVisiable = true), (title = '添加收货地'), (submit = '添加')
          "
          >添加收货地</el-button
        >
        <br /><br />
        <div class="receivingPlace">
          <div v-for="item in allReceivePlace" :key="item.id" class="place">
            <div
              class="place-container"
              @click="highlightDiv(item)"
              :class="{ highlighted: highlightedId === item.id }"
            >
              <div>
                {{ item.province }}{{ item.city }}{{ item.district
                }}{{ item.address }}
              </div>
              <div>{{ item.name }}</div>
              <div>{{ item.telephone }}</div>
              <el-button
                type="danger"
                :icon="Delete"
                size="small"
                style="float: right"
                @click="deleteReceivePlace(item)"
                circle
              />
              <el-button
                type="primary"
                :icon="Edit"
                size="small"
                style="float: right"
                @click="updateReceivePlace(item)"
                circle
              />
            </div>
          </div>
        </div>
      </div>
      <div class="bottom-left">
        <label>购买商品列表</label><br /><br />
        <el-table :data="goodsInfoStore.goodsInfo" style="width: 100%">
          <el-table-column label="商品图像">
            <template #default="{ row }">
              <img :src=row.image style="width: 100px; object-fit: cover;">
            </template>
          </el-table-column>
          <el-table-column label="商品名字" prop="goodsName"> </el-table-column>
          <el-table-column label="商家" prop="businessName"> </el-table-column>
          <el-table-column label="商品数量" prop="goodsNum"> </el-table-column>
          <el-table-column label="商品总价格">
            <template #default="{ row }">
              {{ (row.price * row.goodsNum).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="right">
      <label>结算</label>
      <div>请确认以下信息是否正确：</div>
      <div>商品总价格：{{ totalPrice }}</div>
      <div v-if="chooseReceivePlaceInfo.name">
        收货地址信息：
        <div>收货人：{{ chooseReceivePlaceInfo.name }}</div>
        <div>
          收货地址：{{ chooseReceivePlaceInfo.province
          }}{{ chooseReceivePlaceInfo.city }}{{ chooseReceivePlaceInfo.district
          }}{{ chooseReceivePlaceInfo.address }}
        </div>
        <div>收货人电话号码：{{ chooseReceivePlaceInfo.telephone }}</div>
        <div>收货人email：{{ chooseReceivePlaceInfo.email }}</div>
      </div>
      <el-button plain @click="payVisible = true" :disabled="!chooseReceivePlaceInfo.name" class="purchase-button"> 立即支付 </el-button>
      <el-dialog v-model="payVisible" title="支付界面" width="40%">
        <span
          >此处显示二维码，但由于只是用于学习，因此没有支付环节，点击支付完成即可</span
        >
        <el-dialog
          v-model="emailVisible"
          width="30%"
          title="发送电子邮件验证码确认收货信息"
          append-to-body
        >
          <div class="verification-code">
            <el-input
              v-model="inputVerificationCode"
              style="width: 200px; display: inline-block"
            />
            <el-button
              :disabled="sendVerificationCodeDisabled"
              @click="sendVerificationCode"
              style="margin-left: 10px"
            >
              发送验证码
            </el-button>
            <el-button @click="verifyCode">
              确认
            </el-button>
          </div>
        </el-dialog>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="payVisible = false">取消支付</el-button>
            <el-button type="primary" @click="finishPay">
              支付完成
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 添加收货地 -->
    <el-dialog v-model="addVisiable" :title="title" width="50%" align-center>
      <el-descriptions :column="3" border>
        <el-descriptions-item
          label="收货人姓名"
          label-align="right"
          align="center"
        >
          <el-input v-model="newReceivePlaceInfo.name"></el-input>
        </el-descriptions-item>
        <el-descriptions-item
          label="收货人电话号码"
          label-align="right"
          align="center"
        >
          <el-input v-model="newReceivePlaceInfo.telephone"></el-input>
        </el-descriptions-item>
        <el-descriptions-item
          label="收货地省份+城市"
          label-align="right"
          align="center"
        >
          <el-cascader
            v-model="selectedOptions"
            v-bind:options="pcaTextArr"
            size="large"
            @change="handleChange()"
          />
        </el-descriptions-item>
        <el-descriptions-item
          label="收货人email地址"
          label-align="right"
          align="center"
        >
          <el-input v-model="newReceivePlaceInfo.email"></el-input>
        </el-descriptions-item>
        <el-descriptions-item
          label="具体收货地址"
          label-align="right"
          align="center"
        >
          <el-input v-model="newReceivePlaceInfo.address"></el-input>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancleAddNewReceivePlace">取消</el-button>
          <el-button type="primary" @click="addNewReceivePlace">
            {{ submit }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { Edit, Delete } from "@element-plus/icons-vue";
import { useGoodsInfoStore } from "@/store/goods";
import { ref } from "vue";
import { pcaTextArr } from "element-china-area-data";
import {
  addReceivePlaceService,
  deleteReceivePlaceService,
  searchReceivePlaceService,
  updateReceivePlaceService,
} from "@/api/receivePlace";
import { sendEmailService } from "@/api/email"
import { addOrderService, updateOrderService } from "@/api/order"
import { ElMessage, ElMessageBox } from "element-plus";
import router from "@/router";
import { deleteShoppingCarGoodsService } from "@/api/shoppingCar";
import { updateGoodsService } from "@/api/goods";

const sendVerificationCodeDisabled = ref(false);
const inputVerificationCode = ref("");
const verificationCode = ref("");
const emailVisible = ref(false);
const payVisible = ref(false);
const highlightedId = ref("");
const title = ref("");
const submit = ref("");
const allReceivePlace = ref([]);
const addVisiable = ref(false);
const goodsInfoStore = useGoodsInfoStore();
const selectedOptions = ref([]);
const totalPrice = ref(0);
const payGoodsInfo = ref([]);

const oldReceivePlaceInfo = ref({
  name: "",
  telephone: "",
  province: "",
  city: "",
  district: "",
  email: "",
  address: "",
});

const newReceivePlaceInfo = ref({
  name: "",
  telephone: "",
  province: "",
  city: "",
  district: "",
  email: "",
  address: "",
});

const chooseReceivePlaceInfo = ref({
  name: "",
  telephone: "",
  province: "",
  city: "",
  district: "",
  email: "",
  address: "",
});

const options = {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
  hour12: false, // 24小时制
  timeZone: 'Asia/Shanghai' // 设置时区为上海，即中国标准时间
};

const clearNewReceivePlaceInfo = () => {
  newReceivePlaceInfo.value = {
    name: "",
    telephone: "",
    province: "",
    city: "",
    district: "",
    email: "",
    address: "",
  };
}

const clearOldReceivePlaceInfo = () => {
  oldReceivePlaceInfo.value = {
    name: "",
    telephone: "",
    province: "",
    city: "",
    district: "",
    email: "",
    address: "",
  };
}

const clearChooseReceivePlaceInfo = () => {
  chooseReceivePlaceInfo.value = {
    name: "",
    telephone: "",
    province: "",
    city: "",
    district: "",
    email: "",
    address: "",
  };
}

const getTotalPrice = () => {
  totalPrice.value = goodsInfoStore.goodsInfo.reduce(
    (sum, shoppingCar) => sum + shoppingCar.goodsNum * shoppingCar.price,
    0
  );
  totalPrice.value = parseFloat(totalPrice.value.toFixed(2));
};

getTotalPrice();

const highlightDiv = (item: any) => {
  highlightedId.value = item.id;
  chooseReceivePlaceInfo.value = item;
};

const getAllReceivePlace = async () => {
  const result = await searchReceivePlaceService();
  allReceivePlace.value = result.data;
};

getAllReceivePlace();

const handleChange = () => {
  newReceivePlaceInfo.value.province = selectedOptions.value[0];
  newReceivePlaceInfo.value.city = selectedOptions.value[1];
  newReceivePlaceInfo.value.district = selectedOptions.value[2];
};

const cancleAddNewReceivePlace = () => {
  //取消添加新地址
  addVisiable.value = false;
  clearNewReceivePlaceInfo();
  selectedOptions.value = [];
};

const addNewReceivePlace = async () => {
  if (title.value == "添加收货地") {
    //发送信息到后端
    const result = await addReceivePlaceService(newReceivePlaceInfo.value);
    ElMessage({
      type: result.message !== "操作成功" ? "error" : "success",
      message:
        result.messagee !== "操作成功" ? result.message : "添加收货地址成功",
    });
  } else {
    const result = await updateReceivePlaceService(oldReceivePlaceInfo.value, newReceivePlaceInfo.value);
    ElMessage({
      type: result.message !== "操作成功" ? "error" : "success",
      message:
        result.messagee !== "操作成功" ? result.message : "修改收货地址成功",
    });
  }
  //更新收货地址
  getAllReceivePlace();
  //清空数据
  clearNewReceivePlaceInfo();
  clearOldReceivePlaceInfo();
  selectedOptions.value = [];
  addVisiable.value = false;
};

const updateReceivePlace = (row: any) => {
  newReceivePlaceInfo.value = {
    name: row.name,
    telephone: row.telephone,
    province: row.province,
    city: row.city,
    district: row.district,
    email: row.email,
    address: row.address,
  };
  oldReceivePlaceInfo.value = {
    name: row.name,
    telephone: row.telephone,
    province: row.province,
    city: row.city,
    district: row.district,
    email: row.email,
    address: row.address,
  };
  selectedOptions.value = [row.province, row.city, row.district];
  submit.value = "提交修改";
  title.value = "修改收货信息";
  addVisiable.value = true;
};

const deleteReceivePlace = async (row: any) => {
  //删除收货地
  ElMessageBox.confirm("您确认要删除该收货地信息吗?", "温馨提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      //确认了删除
      const result = await deleteReceivePlaceService(row);
      ElMessage({
        type: result.message !== "操作成功" ? "error" : "success",
        message:
          result.message !== "操作成功" ? result.message : "删除收货地址成功",
      });
      getAllReceivePlace();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "用户取消了删除该收货地址",
      });
    });
};

const finishPay = async() => {
  emailVisible.value = true;
  sendVerificationCodeDisabled.value = false;
  for (const item of goodsInfoStore.goodsInfo) {
    const now = new Date();
    const localTime = now.toLocaleString('sv-SE', options).replace(',', '');
    const data = {
      "customerName": "",
      "businessName": item.businessName,
      "goodsName": item.goodsName,
      "buyTime": localTime,
      "price": item.price,
      "goodsNum": item.goodsNum,
      "arriveTime": "",
      "emailTime": "",
      "deliveryTime": "",
      "shippingTime": "",
      "status": "用户未确认收货地址等信息",
      "email": chooseReceivePlaceInfo.value.email,
      "telephone": chooseReceivePlaceInfo.value.telephone,
      "businessImage": item.image
    }
    const shoppingCarData = new Map([
      ['goods_name', item.goodsName],
      ['business_name', item.businessName],
    ]);
    payGoodsInfo.value.push(data);
    await addOrderService(data);
    await deleteShoppingCarGoodsService(shoppingCarData);
  }
}

const sendVerificationCode = async() => {
  const result = await sendEmailService(chooseReceivePlaceInfo.value.email);
  verificationCode.value = result.data;
  sendVerificationCodeDisabled.value = true;
}

const verifyCode = async() => {
  if(inputVerificationCode.value === verificationCode.value) {
    for (const item of goodsInfoStore.goodsInfo) {
      const index = goodsInfoStore.goodsInfo.findIndex(good => good === item);
      const now = new Date();
      const localTime = now.toLocaleString('sv-SE', options).replace(',', '');
      const data = {
        businessName: item.businessName,
        goodsName: item.goodsName,
        buyTime: payGoodsInfo.value[index].buyTime,
        emailTime: localTime,
        status: "商家还未发货",
      }
      await updateOrderService(data);
    }
    ElMessage({type: "success", message: "购买完成"});
    router.push("/");
  }else {
    ElMessage({type: "error", message: "验证码输入错误，请重试！"});
  }
}
</script>

<style scoped>
.container {
  display: flex;
  height: 100vh;
}

.left {
  display: flex;
  flex-direction: column;
  width: 80%;
}

.top-left {
  height: 30%;
  padding: 20px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 16px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background-color: rgba(157, 199, 219, 0.297);
}

.bottom-left {
  flex: 1;
  padding: 20px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 16px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background-color: aliceblue;
}

.right {
  width: 20%;
  padding: 20px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 16px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  position: relative; /* 为伪元素提供定位上下文 */
}

.right::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 200px; /* 渐变色高度 */
  background: linear-gradient(to bottom, #feb47b, white); /* 渐变色，从上到下 */
  border-radius: 8px 8px 0 0; /* 圆角边框 */
  z-index: 1; /* 确保伪元素在底部 */
}

.right > * {
  position: relative; /* 确保子元素在伪元素之上 */
  z-index: 2; /* 确保内容在伪元素之上 */
}

.receivingPlace {
  display: flex;
  width: 100%;
}

.place {
  margin: 10px;
  display: flex;
  width: calc(25%-10px);
  border: 1px solid #ccc;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

.place-container {
  width: 100%;
  position: relative;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border-color 0.3s;
}

.place-container:hover {
  border-color: blue;
}

.add-place-button {
  margin-left: 10px;
}

.highlighted {
  border-color: red; /* 高亮边框颜色 */
}

.purchase-button {
  color: white;            /* 字体颜色为白色 */
  background-color: rgb(255, 47, 0); /* 背景颜色为橙红色 */
  font-weight: bold;      /* 字体加粗 */
  border: none;           /* 去掉边框（如果需要） */
}

.purchase-button:hover {
  background-color: darkorange; /* 悬停时背景颜色变化（可选） */
}
</style>
